<!--
 * @Author: zhangpeng
 * @Date: 2024-11-14 13:58:53
 * @FilePath: \scientific_research_manager_web\src\views\project\mine\initiateChange.vue
 * @LastEditTime: 2025-01-17 11:19:43
 * @Description: 发起变更
-->
<template>
  <div class="initiate-change" v-loading="loading">
    <MyProjectHeader :project-id="projectId" :project-name="projectName" />

    <div class="initiate-change-content">

      <el-form :model="formDate" label-width="112px" >
        <el-form-item label="变更类型" prop="changeType" >
          <div class="relative z-100">
            <el-checkbox-group v-model="formDate.changeType" :disabled="route.query.type === 'edit'">
              <el-checkbox :value="changeTypeEnum.changeMember" :disabled="formDate.changeType?.includes(changeTypeEnum.projectEnd)">{{ changeTypeMap[changeTypeEnum.changeMember] }}</el-checkbox>
              <el-checkbox :value="changeTypeEnum.projectDelay" :disabled="formDate.changeType?.includes(changeTypeEnum.projectEnd)">{{ changeTypeMap[changeTypeEnum.projectDelay] }}</el-checkbox>
             
              <!-- <el-checkbox :value="changeTypeEnum.changeBudget" :disabled="formDate.changeType?.includes(changeTypeEnum.changeBudget)">{{ changeTypeMap[changeTypeEnum.changeBudget] }}</el-checkbox> -->
              <el-checkbox :value="changeTypeEnum.changeOther" :disabled="formDate.changeType?.includes(changeTypeEnum.projectEnd)">{{ changeTypeMap[changeTypeEnum.changeOther] }}</el-checkbox>
              <el-checkbox :value="changeTypeEnum.projectEnd" :disabled="formDate.changeType?.includes(changeTypeEnum.changeMember) || formDate.changeType?.includes(changeTypeEnum.projectDelay) || formDate.changeType?.includes(changeTypeEnum.changeOther)">{{ changeTypeMap[changeTypeEnum.projectEnd] }}</el-checkbox>
            </el-checkbox-group>
          </div>

        </el-form-item>

        <el-form-item label="    " v-if="formDate.changeType?.includes(changeTypeEnum.changeMember)">
          <div class="w-full mt-[-58px]">
            <ProjectMember :data="formDate.memberDTOList" v-if="!detailLoading && !projectChangeLoading" :manager-name="changeDetail?.managerName"  :dictList="dictList" :project-id="projectId" ref="memberRef" class="!px-0"></ProjectMember>
          </div>
        </el-form-item>

        <el-form-item label="项目变更前时间" v-if="formDate.changeType?.includes(changeTypeEnum.projectDelay)" prop="startTime">
          <el-date-picker v-model="formDate.startTime" type="date" placeholder="项目变更前时间" disabled format="YYYY-MM-DD" value-format="YYYY-MM-DD" />
        </el-form-item>


        <el-form-item label="项目变更后时间" v-if="formDate.changeType?.includes(changeTypeEnum.projectDelay)" prop="endTime">
          <el-date-picker v-model="formDate.endTime" type="date" placeholder="项目变更后时间" :disabled-date="disabledDate" format="YYYY-MM-DD" value-format="YYYY-MM-DD" />
        </el-form-item>

        <el-form-item label="变更原因" prop="changeReason">
          <el-input v-model="formDate.changeReason" type="textarea" placeholder="请输入..."
            :autosize="{ minRows: 5, maxRows: 5 }" :style="{
              width: reasonWidthFixedTypes.includes(formDate.changeType) ? '486px' : '100%'
            }" :maxlength="2000"
            show-word-limit />
        </el-form-item>

        <el-form-item label="变更文件" prop="fileList">
          <FileUpload :is-show-tip="false" drag width="393px" @update:modelValue="update" :model-value="formDate.fileList"/>
        </el-form-item>

      </el-form>
      <div class="h-[72px] bg-white"></div>
      <div class="examine-bar">
        <el-button @click="proxy.$tab.closePage()" v-if="route.query.type !== 'edit'">取消</el-button>
        <el-button type="primary" @click="submit">{{ route.query.type === 'edit' ? '保存' : '发起变更'}}</el-button>
        
      </div>

    </div>
  </div>
</template>

<script lang="ts">
export default defineComponent({
  beforeRouteEnter(to, from, next) {
    if(to.query.type === 'edit'){
      to.meta.title = '编辑变更';
    }
    
    next()
  }
})
</script>

<script setup lang="ts" name="InitiateChange">
import { ref } from 'vue';
import { changeTypeEnum } from '@/utils/constEnum'
import { changeTypeMap } from '@/utils/constText'
import MyProjectHeader from '../components/MyProject/MyProjectHeader.vue'
import ProjectMember from '../components/MyProject/ProjectMemberHasChange.vue'
// import { projectChangeMemberUpdateApi, projectCreateOrUpdateDelayApi, projectCreateOrUpdateStopApi, projectCreateOrUpdateFundingApi } from '@/api/project'
import { projectChangeMemberUpdateApi} from '@/api/project'
import { getBaseDetailsApi, getDicListApi, projectChangeDetailApi } from '@/api/project'
import { ProjectChangeMemberUpdateDTO, DictionaryListRespVO } from '@/api/project/types'


const { proxy } = getCurrentInstance();
const route = useRoute()
const projectId = ref(route.query.projectId as unknown as string)
const projectName = ref(route.query.projectName as unknown as string)
const memberRef = ref()

const reasonWidthFixedTypes = [changeTypeEnum.projectDelay, changeTypeEnum.projectEnd, changeTypeEnum.changeOther]  //  原因宽度固定的变更类型

const loading = computed(() => {
  return detailLoading.value || memberLoading.value || projectChangeLoading.value
})

const changeDetail = ref({})

const dictList = ref<DictionaryListRespVO[]>([])

const formDate = ref({
  changeType: [],
  startTime: undefined,
  endTime: undefined,
  fileList: [],
  changeReason: '',
  memberDTOList: []
})
const changeId = ref('')


const fileIds = computed(() => {
  let list = formDate.value.fileList?.map((i) => {
    return i.id
  })
  return list
})

const disabledDate = (time: Date) => {
  // return time.getTime() < (formDate.value.startTime! ? new Date(formDate.value.startTime!)?.getTime() : new Date().getTime())
  return time.getTime() < new Date(formDate.value.startTime!)?.getTime()
}

// 获取相关字典
const { run: getDicList } = useRequest(getDicListApi, {
  manual: true,
  onSuccess: (res: DictionaryListRespVO[]) => {
    dictList.value = res
  }
})

// 项目详情
const { run: projectDetail, loading: detailLoading } = useRequest(getBaseDetailsApi, {
  manual: true,
  onSuccess: (res) => {
    changeDetail.value = res
    formDate.value.startTime = res?.conclusionTime
    // formDate.value.endTime = res?.conclusionTime
  }
})


// 关闭页签
function close() {
  proxy.$modal.msgSuccess(route.query.type === 'edit' ? "保存成功" : "提交成功");
  proxy.$tab.closePage();
}

// 成员变更
const { run: projectChangeMemberUpdate,  loading: memberLoading } = useRequest(projectChangeMemberUpdateApi, {
  manual: true,
  debounceWait: 500,
  onSuccess: (res) => {
    if (res?.id) {
      close()
    }
  }
})

// 变更详情
const { run: projectChangeDetail, loading: projectChangeLoading } = useRequest(projectChangeDetailApi, {
  manual: true,
  onSuccess: (res) => {
   formDate.value.endTime = res?.delayAfterDTOList?.[0]?.endTime
   formDate.value.changeReason = res?.delayAfterDTOList?.[0]?.endTime
   formDate.value.fileList = res?.attachmentFileInfoDTOList
   formDate.value.changeReason = res?.changeReason
   formDate.value.changeType = res?.changeType
   formDate.value.memberDTOList = res?.memberAfterDTOList
   changeId.value = res?.id
  //  changeType: [],
  // startTime: undefined,
  // endTime: undefined,
  // fileList: [],
  // changeReason: '',
  }
})


// // 项目延期
// const { run: projectCreateOrUpdateDelay, loading: delayLoading } = useRequest(projectCreateOrUpdateDelayApi, {
//   manual: true,
//   debounceWait: 500,
//   onSuccess: (res) => {
//     if (res?.id) {
//       close()
//     }
//   }
// })

// // 项目终止
// const { run: projectCreateOrUpdateStop, loading: stopLoading } = useRequest(projectCreateOrUpdateStopApi, {
//   manual: true,
//   debounceWait: 500,
//   onSuccess: (res) => {
//     if (res?.id) {
//       close()
//     }
//   }
// })

// // 项目经费变更
// const { run: projectCreateOrUpdateFunding, loading: pdateFundingLoading } = useRequest(projectCreateOrUpdateFundingApi, {
//   manual: true,
//   debounceWait: 500,
//   onSuccess: (res) => {
//     if (res?.id) {
//       close()
//     }
//   }
// })

// {
//     "appId": "1846826548489199686",
//     "id": "1863418097504276482",
//     "name": "top1.jpg",
//     "url": "https://dev-sciminio.metaobe.com:9000/scientific-research-manager/20241202/1/11/1863418096950628353/top1.jpg",
//     "uid": 1733108469493,
//     "status": "success"
// }

// 上传文件变化
function update(val) {
  formDate.value.fileList = val
}


async function submit() {
  if(!formDate.value.changeType?.length){
    return ElMessage({ message: '请选择变更类型', type: 'error' })
  }
  const params = {
    projectId: projectId.value,
    fileIds: fileIds.value,
    isDirectSubmit: true,  //  是否直接提交;现阶段都是直接提交,所以传默认true
    changeType: formDate.value.changeType,
    changeReason: formDate.value.changeReason
  } as  ProjectChangeMemberUpdateDTO

  //  人员替换
  if(formDate.value.changeType?.includes(changeTypeEnum.changeMember)){
    const res = await  memberRef.value?.validate()
    if (!res) {
      ElMessage.error('请完善内容')
      return false
    }
    params.memberDTOList = memberRef.value?.memberDTOList //  成员List
  }
  
  //  项目延期
  if(formDate.value.changeType?.includes(changeTypeEnum.projectDelay)){
    if (!formDate.value.endTime) {
      ElMessage.error('项目变更后时间不能为空')
      return false
    }
    params.endTime = formDate.value.endTime //  延期后时间
  }

  // 修改时参传入id
  if(route.query.type === 'edit'){
    params.id = changeId.value
  }

  if (!formDate.value.changeReason?.trim()) {
    ElMessage.error('变更原因不能为空')
    return false
  }

  projectChangeMemberUpdate(params)
  // switch (formDate.value.changeType) {
  //   case changeTypeEnum.changeMember: { //  人员替换
  //     params.memberDTOList = memberRef.value?.memberDTOList //  成员List
  //   //  return console.log(params)
  //     projectChangeMemberUpdate(params)
  //   }
  //     break;

  //   case changeTypeEnum.projectDelay: { //  项目延期
  //     params.endTime = formDate.value.endTime //  延期后时间
  //     // return console.log(params)
  //     projectCreateOrUpdateDelay(params)
  //   }
  //     break;

  //   case changeTypeEnum.projectEnd: { //  项目终止
  //     // return console.log(params)
  //     projectCreateOrUpdateStop(params)
  //   }
  //     break;

  //   case changeTypeEnum.changeBudget: { //  经费变更
  //     params.fundingDTOList = budgetRef.value?.fundingDTOList  //经费List
  //     // return console.log(params)
  //     projectCreateOrUpdateFunding(params)
  //   }
  //     break;

  //   case changeTypeEnum.changeOther: { //  其他变更
  //     // return console.log(params)
  //     projectCreateOrUpdateStop(params)
  //   }
  //     break;

  //   default:
  //     break;
  // }
}

onMounted(() => {
  projectDetail({ id: route.query.projectId as unknown as string })
  if(route.query.type === 'edit'){
    projectChangeDetail({ projectId: route.query.projectId as unknown as string })
  }
  
  getDicList({})
})
</script>

<style lang="scss" scoped>
.initiate-change {
  --at-apply: bg-white;
  min-height: 100%;

  &-content {
    --at-apply: px-[20px] pb-[20px] pt-[40px];
  }
}

.examine-bar {
  border-top: 1px solid #E5E6EB;
  --at-apply: fixed bottom-0 left-0 right-0 h-[72px] flex items-center justify-center bg-white z-1999;

  :deep(.el-button) {
    height: 32px;
  }
}

:deep(.el-form-item--default){
  margin-bottom: 20px;
}
</style>